<?php
// 订单相关管理
namespace Store\Controller;
use Think\Controller;
class ShopController extends CommonController {	
     function _initialize() {
        parent::_initialize();
        $this->nav_model = D("store_type");
   
    }
   /**
     * 商品列表
     */
    public function index(){
        $shop   =   D('shop');
        
        $storeArray  =   $this->storeArray;
        $where ='ishidden=0 and store_id='.$storeArray['id'];
        $store = D("store");//店铺信息
        $title = $_GET['title'];
		
		if($title === iconv('utf-8', "utf-8", iconv("utf-8", 'utf-8', $title))){
			$title=$title;
		}else{
			$title= iconv("gbk","utf-8",$title);
		}
		
        $title  =   preg_replace('/\//',' ',$title);
        if( $title ){
            $titleArray =   explode(' ',$title);
            if( $titleArray ){
                foreach ( $titleArray AS $key=>$row ){
                    $where  .=  $row != ''?' AND title LIKE "%'.$row.'%"':'';
                }
            }
        }
      
        $where  .=  I('get.id') !== ''?' AND id = "'.I('get.id').'"':'';
        if(I('get.store_type_id') >=0&&I('get.store_type_id')!=null){
        	$where  .= ' AND store_type_id = "'.I('get.store_type_id').'"';
        }
     
     
        $_GET['title']  =   implode('_',$titleArray);
        $count      = $shop->where($where)->count();
        $this->assign('count',$count);
        $Page       = new \Think\Page($count,25);// 实例化分页类 传入总记录数
        $show       = $Page->show1();// 分页显示输出
        $array  =   $shop
        			->field("*")
        			->where($where)
        			->order('id DESC')
        			->limit($Page->firstRow.','.$Page->listRows)
        			->select();
        //查询商品所属的店铺  添加时间：2016-12-23  添加人：毕玉
        foreach ( $array AS $key=>$row ){
            $storeinfo = $store->field("title")->where("id=".$row["store_id"])->find();
            $array[$key]["storename"] =$storeinfo["title"];
        }
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('array',$array);
      
      
      	
      	$result = $this->nav_model->where("shore_id=".$storeArray['id'])->order(array("listorder" => "ASC"))->select();
        import("Think.Tree");
        $tree = new \Tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        foreach ($result as $r) {
          	$path=explode('-',$r['path']);
          	if(I('get.store_type_id')==$r['id']){
          		$r['select']='selected';
          	}else{
          		$r['select']='';
          	}
           	$array_type[] = $r;
        }
    	
        $tree->init($array_type);
        $str = "<option value='\$id' \$select>\$spacer\$label</option>";
        $categorys = $tree->get_tree(0, $str);
        $this->assign("categorys", $categorys);
        
        
        $this->assign('title','商品列表');
        $this->display();
    }

    /**
     * 添加
    */
    function add(){
        if( $_GET['id'] ){
            $this->assign('title','修改商品');
            $current= M()->field('shop.*,ShopContent.content,ShopContent.config,ShopContent.gallery,ShopContent.story_content,ShopContent.story_title,story_exprot,story_img,brand.name AS brand_name,stroe.title as btitle')
            ->table(' __SHOP__ AS shop ')
            ->join(' LEFT JOIN __SHOP_CONTENT__ AS ShopContent ON ( ShopContent.shop_id = shop.id ) ')
            ->join(' LEFT JOIN __BRAND__ AS brand ON ( brand.id = shop.brand_id ) ')
            ->join(' LEFT JOIN __STORE__ AS stroe ON ( stroe.id = shop.store_id ) ')
            ->where('shop.id = '.$_GET['id'])->find();
	        $this->assign('current',$current);
	        //当前配置属性
	        $currentConfig  =   json_decode($current['config'],true);
	        $this->assign('currentConfig',$currentConfig);
        }else{
            $this->assign('title','添加商品');
        }
        //获取一级分类列表
        $ticketType =   D('TicketType');
        $ticketTypeArray=   $ticketType->where(' ishidden = 0 AND bid = 0')->order(' sort ASC ')->select();
        $this->assign('ticketTypeArray',$ticketTypeArray);
        //获取品牌列表
        $brand =   D('Brand');
        $where  =   'ishidden = 0';
        $brandArray    =   $brand->field('id,name')->where($where)->order(' name ASC')->select();
        $this->assign('brandArray',$brandArray);
		//获取运费模版列表
		$transport=M('transport');
		$storeArray  =   $this->storeArray;

        $shop_t_f=M('shop')->where('id='.$_GET['id'].' and ishidden=0 and store_id='.$storeArray['id'])->select();
        if($shop_t_f==null&&$_GET['id']){
            $this->error('当前店铺下无该产品');
        }

		$transport_list=$transport->where('store_id='.$storeArray['id'])->select();
		$this->assign('transport_list',$transport_list);
		$this->assign('store_id',$storeArray['id']);
		
        //获取店铺列表
        $store =   D('store');
       
        $Storearray    =   $store->field('id,title')->order(' id asc')->select();
        $this->assign('Storearray',$Storearray);
       //获取所有商品
        $shop_list=M('shop')->where('ishidden=0 and store_id='.$storeArray['id'])->select();
        $this->assign('shop_list',$shop_list);

        if( $_GET['id'] ){
            $ticketConfig   =   D('TicketConfig');
            $arrayFlag  =   clearArrayNull(explode(',',$current['type_id']));
            $currentTypeId  =   implode(',',$arrayFlag);
            $where  =   'ishidden = 0 AND is_end=1 AND id IN ( '.$currentTypeId.' )';
            $typeArray  =   $ticketType->where($where)->order('id DESC')->select();
            $type_ids;
            //去属性重复
            foreach ($typeArray as $key => $value) {
                if(!in_array($value['type_id'], $type_ids)){
                     $type_ids[$key]=$value['type_id'];
                }
            }
            $configArrays;

            foreach ($type_ids as $key => $value) {
                 $newwhere     =   'ishidden = 0 AND type_id IN ( '.$value.' )';
                 $configArray   =   $ticketConfig->where($newwhere)->order('id DESC')->select();
                 if($configArrays){
                    $configArrays =array_merge($configArrays,$configArray);
                 }else{
                    $configArrays =$configArray;
                 }
                  
                
            }
        
            $this->assign('configArray',$configArrays);

	        //获取当前商品最后分类
	        $currentTypeArray	=	$ticketType->field('id,name')->where(' id IN ('.$currentTypeId.') AND is_end = 1')->select();

	        $this->assign('currentTypeArray',$currentTypeArray);
        }

        $SKU_View=$this->CreateSKUView();
        
        $this->assign('SKU_View',$SKU_View);

    
        $this->display();
    }

    /**
     * 添加保存
     */
    function save(){
        $storeArray  =   $this->storeArray;

        $shop   =   D('shop');
        $ticketType	 =		D('TicketType');
        $ShopContent   =   D('ShopContent');

        //处理分类ID问题
        if( I('post.type_id') ){
            $type_id	=	implode(',',I('post.type_id'));
            $ticketTypeArray	=	$ticketType->field('bids')->where(' id IN ('.$type_id.') ')->select();
            if( $ticketTypeArray ){
                $flag	=	'';
                foreach ( $ticketTypeArray AS $key=>$row ){
                    $flag.=	$row['bids'].',';
                }
            }
            $flagArray	=	explode(',',$flag);
            $arrayFlag		=	clearArrayNull($flagArray);
            $typeIdFlag	=	implode(',',$arrayFlag);
        }
        $id                                 =   $_POST['id'];
        $new_data['title']					=	I('post.title');
        $new_data['keywords']				=	I('post.keywords');
        $new_data['description']            =   I('post.description');
        $new_data['image']					=	I('post.thumb');
        $new_data['type_id']				=	','.$typeIdFlag.',';
        $new_data['brand_id']               =   I('post.brand_id');
        $new_data['store_id']          =   $storeArray['id'];

        $new_data['click_num']               =   I('post.click_num');
        $new_data['price']                  =   I('post.price');
        $new_data['oprice']                 =   I('post.oprice');
        $new_data['start']                  =   strtotime(I('post.start'));
        $new_data['end']                    =   I('post.end')?strtotime(I('post.end')):'';

        $new_data['num']                    =   I('post.num');
        $new_data['xz_num']                 =   I('post.xz_num');
        $new_data['qp_num']                 =   I('post.qp_num');
        $new_data['sale_num']               =   I('post.sale_num');
        $new_data['px_id']                  =   I('post.px_id');

        $new_data['dikouquan']            =   I('post.dikouquan');

        $new_data['isindex']			    =	I('post.isindex');
        //店铺单有 运费设置
        if(I('post.freight')==0){
            $new_data['goods_freight']			    =	I('post.g_freight');
            $new_data['transport_id']			    =	0;
        }
        if(I('post.freight')==1){
            $new_data['goods_freight']			    =	0;
            $new_data['transport_id']			    =	I('post.mbrand_id');
        }
        // 运费设置end

        //店铺单有 代言设置
        $new_data['redenvelope']            =   I('post.redenvelope');
        $new_data['envelope_product_id']            =   I('post.envelope_product_id');
        $new_data['envelope_product_type']            =   I('post.envelope_product_type');
        $new_data['envelope_type']            =   I('post.envelope_type');
        //代言设置end

        $new_data['mian_send']             =   I('post.mian_send');
        $new_data['tuanselect']             =   I('post.tuanselect');
        $new_data['tuan_num']               =   I('post.tuan_num');
        $new_data['tuan_price']             =   I('post.tuan_price');
        $new_data['tuan_buynum']            =   I('post.tuan_buynum');
        $new_data['tuanz_buysale']          =   I('post.tuanz_buysale');
        $new_data['tuanz_starttime']          =   I('post.tuanz_starttime')?strtotime(I('post.tuanz_starttime')):'';
        $new_data['tuanz_endtime']          =   I('post.tuanz_endtime')?strtotime(I('post.tuanz_endtime')):'';
        if($new_data['dikouquan']>$new_data['price']){
            $this->ajax_r(0,"抵扣券不能大于商品售价");
        }
        if($new_data['redenvelope']>$new_data['price']){
            $this->ajax_r(0,"红包不能大于商品售价");
        }
        if($new_data['store_id']=='0'){
            $this->ajax_r(0,"请选择所属店铺");
        }
        if($new_data['image']==null){
            $this->ajax_r(0,"请上传商品图片");
        }
        if($new_data['brand_id']=='0'){
            $this->ajax_r(0,"请选择商品品牌");
        }
        if($new_data['tuanselect'] =='1'&&$new_data['tuan_num']==null){
            $this->ajax_r(0,"请输入开团人数");
        }
        if($new_data['tuanselect'] =='1'&&$new_data['tuan_price']==null){
            $this->ajax_r(0,"请输入团购价格");
        }
        if($new_data['tuanselect'] =='1'&&$new_data['tuan_buynum']==null){
            $this->ajax_r(0,"请输入限制购买数量");
        }
//      if($new_data['tuanselect'] =='1'&&$new_data['tuanz_buysale']==null){
//          echo '0|||请输入团长优惠';die();
//      }
        if($new_data['tuanselect'] =='1'&&$new_data['tuanz_starttime']==null){
            $this->ajax_r(0,"请输入开团开始时间");
        }
        if($new_data['tuanselect'] =='1'&&$new_data['tuanz_endtime']==null){
            $this->ajax_r(0,"请输入开团结束时间");
        }



        //处理配置属性
        $configArray	=	I('post.config');

        $new_data['search_tag']='';
        $arrayFlag	=	array();
        if( $configArray ){
            foreach( $configArray AS $key=>$row ){
                $flag	=	explode(',',$row);
                $arrayFlag[$flag[0]]['title']				=	urlencode($flag[1]);
                $arrayFlag[$flag[0]]['content']		=	urlencode(I('post.config'.$flag[0]));
                $new_data['search_tag'].=I('post.config'.$flag[0]).',';
            }
        }

        $new_data1['config']	=urldecode(	json_encode($arrayFlag));
        $new_data1['content']	=	preg_replace('/<br \/>/','',$_POST['content']);
        $new_data1['story_content']	=	preg_replace('/<br \/>/','',I('post.story_content'));
        $new_data1['story_title']	=	I('post.story_title');
        $new_data1['story_img']	=	I('post.story_img');
        $new_data1['story_exprot']	=	I('post.story_exprot');
        $new_data1['gallery']	=	I('post.gallery');
        $new_data1['story_time']	=	time();
        //处理sku
        //库存
        $SKU_Stock=I('post.SKU_Stock');
        //价格
        $SKU_Price=I('post.SKU_Price',0,'floatval');

        //团购价格

        $SKU_Price_tuan=I('post.SKU_Price_tuan',0,'floatval');
        //SKU编号
        $SKU_SeriesNum=I('post.SKU_SeriesNum');
        //颜色
        $SKU_SeledItem['SKU_Style']=I('post.SKU_Style');
        $SKU_SeledItem['SKU_Style_Cus']=I('post.SKU_Style_Cus');
        $SKU_SeledItem['SKU_Style_Idx']=I('post.SKU_Style_Idx');
        $SKU_StyleName=I('post.SKU_StyleName');
        //规格
        $SKU_SeledItem['SKU_Spec_Idx']=I('post.SKU_Spec_Idx');
        $SKU_SeledItem['SKU_Spec']=I('post.SKU_Spec');
        $SKU_SeledItem['SKU_Spec_Cus']=I('post.SKU_Spec_Cus');
        $SKU_SpecName=I('post.SKU_SpecName');
        //图片
        $SKU_Pic=$_POST['UpFilePathInfo']['SKU_Pic'];



        //图片保存路径

        //判断是否有颜色样式单品选中项并生成Json代码
        $SKU_StyleCount=count($SKU_SeledItem['SKU_Style']);

        if($SKU_SeledItem['SKU_Style']!==''){

            //配置项信息处理，这里处理的是选择的SKU单品属性项和对应的图片信息
            for($i=0;$i<$SKU_StyleCount;$i++){
                $thumbPicPath_M='';
                $thumbPicPath_S='';

                $SKU_Pic[$i]=$SKU_Pic[$i]=='null'?$new_data['image']:$SKU_Pic[$i];
                $SKU_Pic[$i]=$SKU_Pic[$i]==''?$new_data['image']:$SKU_Pic[$i];
                $SKU_Img=$SKU_Pic[$i];
                //缩略图生成

                if(!empty($SKU_Pic)){

                    //图片全地址
                    $SKU_Img_Path=$_SERVER['DOCUMENT_ROOT'].$SKU_Pic[$i];
                    //保存地址

                    $SKU_Img=$SKU_Pic[$i];

                    if(file_exists($SKU_Img_Path)){
                        $thumbPicPath_S_Path=$SKU_Img_Path.'-s_thumb.jpg';
                        $thumbPicPath_M_Path=$SKU_Img_Path.'-m_thumb.jpg';
                        $thumbPicPath_S=$SKU_Img.'-s_thumb.jpg';
                        $thumbPicPath_M=$SKU_Img.'-m_thumb.jpg';
                    }
					
                    //文件名已经存在时跳过
                    if(!file_exists($thumbPicPath_S_Path)&&file_exists($SKU_Img_Path)){
						
                        getPicThumb($SKU_Img_Path,120,120,1,$thumbPicPath_S_Path);
                    }
                    if(!file_exists($thumbPicPath_M_Path)&&file_exists($SKU_Img_Path)){
                        getPicThumb($SKU_Img_Path,400,400,1,$thumbPicPath_M_Path);
                    }

                }


                $style[]=array(
                    'SKU_Style_Idx'=>$SKU_SeledItem['SKU_Style_Idx'][$i],
                    'defaultValue'=>$SKU_SeledItem['SKU_Style'][$i],
                    'modifyValue'=>$SKU_SeledItem['SKU_Style_Cus'][$i],
                    'SKU_Img'=>$SKU_Img,
                    'SKU_ThumbImg_M'=>$thumbPicPath_M,
                    'SKU_ThumbImg'=>$thumbPicPath_S
                );
                //生成添加或者更新时对应sku表中sku_img的图片数据，由于是json，这里需要重新生成一个数组
                $skuImgData[]=array(
                    'SKU_Img'=>$SKU_Img,
                    'SKU_ThumbImg_M'=>$thumbPicPath_M,
                    'SKU_ThumbImg'=>$thumbPicPath_S
                );
            }
            $SKU_Info['SKU_Style']=$style;


        }else{
            $SKU_Info['SKU_Style']=null;
        }



        //判断是否有规格单品选中项生成Json代码
        $SKU_SpecCount=count($SKU_SeledItem['SKU_Spec']);
        if($SKU_SeledItem['SKU_Spec']!==''){
            for($i=0;$i<$SKU_SpecCount;$i++){
                $spec[]=array('SKU_Spec_Idx'=>$SKU_SeledItem['SKU_Spec_Idx'][$i],
                    'defaultValue'=>$SKU_SeledItem['SKU_Spec'][$i],
                    'modifyValue'=>$SKU_SeledItem['SKU_Spec_Cus'][$i]);
            }
            $SKU_Info['SKU_Spec']=$spec;
        }else{
            $SKU_Info['SKU_Spec']=null;
        }

        if($SKU_SeledItem['SKU_Spec']!==''||$SKU_SeledItem['SKU_Style']!==''){
            //处理单品项表单数据，转为数据行，这里以必然出现的表单项为长度进行遍历
            for($i=0;$i<count($SKU_Stock);$i++){
                $SKU_Price[$i]=$SKU_Price[$i]==''?$new_data['price']:$SKU_Price[$i];
                $SKU_Price_tuan[$i]=$SKU_Price_tuan[$i]==''?$new_data['price']:$SKU_Price_tuan[$i];

                $SKU_Stock[$i]=$SKU_Stock[$i]==''?0:$SKU_Stock[$i];
                $SKU_Form[]=array(
                    'sku_spec'=>$SKU_SpecName[$i],
                    'sku_style'=>$SKU_StyleName[$i],
                    'sku_stock'=>$SKU_Stock[$i]==''?$new_data['num']:$SKU_Stock[$i],
                    'sku_price'=>$SKU_Price[$i],
                    'sku_price_tuan'=>$SKU_Price_tuan[$i],
                    'sku_series'=>$SKU_SeriesNum[$i]
                );
            }
            $SKU_Info['SKU_Form']=$SKU_Form;

            //加入SKU单品项更新数据
            $new_data['shop_sku']=json_encode($SKU_Info);
        }else{
            $SKU_Info['SKU_Form']=null;

            //加入SKU单品项更新数据
            $new_data['shop_sku']=null;
        }

        if($id){
            $flag1=$shop->where(' id = '.$id)->save($new_data);

            $new_data1['shop_id'] =   $id;
            $rs=$ShopContent->where(' shop_id = '.$id)->find();
            if($rs){
                $flag2= $ShopContent->where(' shop_id = '.$id)->save($new_data1);
            }else{
                $flag2= $ShopContent->add($new_data1);
            }
        }else{
            $new_data['addtime']    =   time();
            $flag1=$shop->add($new_data);

            $new_data1['shop_id'] = $flag1;
            $flag2=$ShopContent->add($new_data1);
        }




        $this->SKU_model=M('shop_sku');
        //开启事务批量插入数据
        $this->SKU_model->startTrans();

        //如果存在SKU单品数据，则为其添加对应所属的商品ID
        if(count($SKU_Form)>0){

            foreach ($SKU_Form as $key => $value) {
                $map['shop_id']=$new_data1['shop_id'];
                $map['sku_idx']=$key;

                $rs_sku= $this->SKU_model->where($map)->find();

                //判断是插入数据还是编辑更新数据
                if(!$rs_sku){
                    $value['shop_id']=$new_data1['shop_id'];
                    $value['sku_idx']=$key;
                    $value['sku_img']=!empty($skuImgData[$key])?json_encode($skuImgData[$key]):null;
                    $skuResult=$this->SKU_model->add($value);

                }else{
                    $value['sku_img']=!empty($skuImgData[$key])?json_encode($skuImgData[$key]):null;
                    $skuResult=$this->SKU_model->where(array('shop_id'=>$new_data1['shop_id'],'sku_idx'=>$key,'sku_id'=>$rs_sku['sku_id']))->save($value);
                }
            }
            if($skuResult===false){
                $this->SKU_model->rollback();
                $this->ajax_r(0,"保存商品失败");
            }else{
                $this->SKU_model->commit();
                //不存在SKU单品数据时直接提交商品数据
                $this->ajax_r(1,"保存商品成功",array('url' => U('Shop/index')));
            }
        }else{
            //不存在SKU单品数据时直接提交商品数据
            $this->ajax_r(1,"保存商品成功",array('url' => U('Shop/index')));
        }
    }



    //创建SKU表单html代码

    private function CreateSKUView(){
        $i=0;
        $colorCode='';
        $SpecCode='';
        $SKU_Style=C('GOODS_COLOR');
        $SKU_Spec=C('GOODS_SPEC');

        //取出用户数据，一个是勾选的单品项属性,这个数据解析交给客户端处理，第二个是单品项的对应数据
        $seledSKUOption=json_encode(array('SKU_Color'=>array('blue'=>'蓝色','black'=>'黑色'),'SKU_Spec'=>array('SPEC-2'=>'规格二')));
        $SKU_Data;
        //根据用户数据生成视图代码


        foreach ($SKU_Style as $key => $value) {
            $colorCode.='<label class="checkbox-inline"><input name="SKU_Style[]" value="'
            .$value.'" type="checkbox" data-tag="'.$key.'" data-sku="SKU_Style" ><span>'.$value.'</span>
            <input type=hidden value="'.$value.'" data-tag="modifyValue">
            <input type=hidden value="'.$i.'" data-tag="idx"></label>';
            $i++;
        }

        $i=0;

        foreach ($SKU_Spec as $key => $value) {
            $SpecCode.='<label class="checkbox-inline"><input name="SKU_Spec[]" value="'
            .$value.'" type="checkbox" data-tag="'.$key.'" data-sku="SKU_Spec" ><span>'.$value.'</span>
            <input type=hidden value="'.$value.'" data-tag="modifyValue">
            <input type=hidden value="'.$i.'" data-tag="idx"></label>'; 
            $i++;       
        }

        $colorCode='<div id="SKU_Style" class="checkbox" data-skutype="sub">'.$colorCode.'</div>';
        $SpecCode='<div id="SKU_Spec" class="checkbox" data-skutype="main">'.$SpecCode.'</div>';
        $this->assign('seledSKUOption',$seledSKUOption);

        return $colorCode.$SpecCode;
    }

      /**
     * ajax获取商品分类
     */
    function ajaxGetTicketType(){
        //获取子分类列表
        $ticketType =   D('TicketType');
        $where  =   ' ishidden = 0 AND bid = '.I('get.type_id');
        $where  .=  I('get.keywords')?' AND name LIKE "%'.I('get.keywords').'%"':'';
        $ticketTypeArray=   $ticketType->where($where)->order(' sort ASC ')->select();
        $string =   count($ticketTypeArray).'|||<div class="fl subtype">
        <ul>';
        if( $ticketTypeArray ){
            foreach ( $ticketTypeArray AS $key=>$row ){
                $string .=  '<li data="'.$row['id'].'">'.$row['name'].'></li>';
            }
        }
        $string .=  '</ul>
        </div>';
        echo $string;
    }

    /**
     * ajax获取商品品牌
     */
    function ajaxGetBrand(){
        //获取子分类列表
        $brand =   D('Brand');
        $where  =   ' ishidden = 0 ';
        $where  .=  I('get.keywords')?' AND name LIKE "%'.I('get.keywords').'%"':'';
        $where  .=  I('get.is_for_recycle')?' AND is_for_recycle = "1"':'';
        $brandArray=   $brand->where($where)->order(' sort ASC ')->select();
        $string =   '<div class="fl subtype">
        <ul>';
        if( $brandArray ){
            foreach ( $brandArray AS $key=>$row ){
                $string .=  '<li data="'.$row['id'].'">'.$row['name'].'</li>';
            }
        }
        $string .=  '</ul>
        </div>';
        echo $string;
    }

     function zuzhuang(){
        if( I('get.type') == 'save' ){
            $this->zuzhuangSave();
        }else{
           $this->display();
        }
    }

    function zuzhuangSave(){
        $zuzhuangString    =   I('get.zuzhuangString');
        $array =   explode(',',$zuzhuangString);
        $string    =   getCount($array);
        $count =   count(explode(',', $string));
        echo $count.'|||'.$string;
    }

    
     function ajaxGetConfig(){
    	$id	=	I('get.type_id');
        $ticketType=M('ticket_type');
        $where  =   'id IN ( '.$id.' )';
        $t_type=$ticketType->where($where)->select();
        $type_ids;
        //去属性重复
        foreach ($t_type as $key => $value) {
            if(!in_array($value['type_id'], $type_ids)){
                 $type_ids[$key]=$value['type_id'];
            }
        }
        $type_id=implode(',',$type_ids);
        //获取配置属性列表
        $ticketConfig   =   D('TicketConfig');
        $where 	=   'ishidden = 0 AND type_id IN ( '.$type_id.' ) ';
    	$configArray	=	$ticketConfig->field('id,title,is_write,content')->where($where)->order('id DESC')->select();
    	$string	=	'';
    	if( $configArray ){
    		foreach ( $configArray AS $key=>$row ){
    			$is_write	=	$row['is_write'] == '1'?'text':'hidden';
    			$string	.=	'<div><span>'.$row['title'].':</span>
			    				<input name="config[]" type="hidden" value="'.$row['id'].','.$row['title'].'" >
			    				<input name="config'.$row['id'].'" id="config'.$row['id'].'" type="'.$is_write.'" value="" > ';
    			$subArray	=	explode(',',$row['content']);
              
    			if( $subArray ){
    				foreach ( $subArray AS $key=>$row1 ){
    					if( !$row1 ){ continue; }
    					$string	.=	'<span class="btn  btn-xs config'.$row['id'].'" data="'.$row['id'].'">'.$row1.'</span> ';
    				}
    			}
    			$string	.=	'</div><div class="space-4"></div>';
    		}
    	}
    	echo $string;
    	die();
       
    }
	//店铺分类
   	public function type(){
   		$storeArray  =   $this->storeArray;
        
        $result = $this->nav_model->where("shore_id=".$storeArray['id'])->order(array("listorder" => "ASC"))->select();
        import("Think.Tree");
        $tree = new \Tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        foreach ($result as $r) {
            $r['str_manage'] = '<a href="' . U("Shop/type_add", array("parentid" => $r['id'])) . '"  class="btn btn-primary btn-xs">'.添加子菜单.'</a>  <a href="' . U("Shop/type_edit", array("id" => $r['id'],"parentid"=>$r['parentid'])) . '"  class="btn btn-info btn-xs">'.编辑.'</a>  <a class="js-ajax-delete btn btn-warning btn-xs" href="' . U("Shop/type_del", array("id" => $r['id'])) . '">'.删除.'</a> ';
            $r['status'] = $r['status'] ?显示 : 隐藏;
            $path=explode('-',$r['path']);
            $num=count($path);
            $array[] = $r;
        }
    
        $tree->init($array);
        $str = "<tr>
                <td><input name='listorders[\$id]' type='text' size='3' value='\$listorder' class='input input-order'></td>
                <td>\$id</td>
                <td >\$spacer\$label</td>
                <td>\$status</td>
               
                <td>\$str_manage</td>
            </tr>";
        $categorys = $tree->get_tree(0, $str);
        $this->assign("categorys", $categorys);
        $this->assign('title','导航管理');
        $this->display();
   	}
   	
   	public function type_add(){
   		$storeArray  =   $this->storeArray;
   		$result = $this->nav_model->where("shore_id=".$storeArray['id'])->order(array("listorder" => "ASC"))->select();
        import("Think.Tree");
        $tree = new \Tree();
        $tree->icon = array('&nbsp;│ ', '&nbsp;├─ ', '&nbsp;└─ ');
        $tree->nbsp = '&nbsp;';
        $parentid=I("get.parentid");
        foreach ($result as $r) {
            $r['str_manage'] = '<a href="' . U("Menu/add", array("parentid" => $r['id'], "menuid" => I("get.menuid"))) . '">添加子菜单</a> | <a href="' . U("Menu/edit", array("id" => $r['id'], "menuid" => I("get.menuid"))) . '">修改</a> | <a class="js-ajax-delete" href="' . U("Menu/delete", array("id" => $r['id'], "menuid" => I("get.menuid"))) . '">删除</a> ';
            $r['status'] = $r['status'] ? "显示" : "隐藏";
            $r['selected'] = $r['id']==$parentid?"selected":"";
            $array[] = $r;
        }
            
        $tree->init($array);
        $str = "<tr>
                <td><input name='listorders[\$id]' type='text' size='3' value='\$listorder' class='input'></td>
                <td>\$id</td>
                <td >\$spacer\$label</td>
                <td>\$status</td>
                <td>\$str_manage</td>
            </tr>";
        $str="<option value='\$id' \$selected>\$spacer\$label</option>";
        $nav_trees = $tree->get_tree(0, $str);
        $this->assign("nav_trees", $nav_trees);
            
        $ticketType = D('TicketType');
        $ticketType_array = $ticketType->where('ishidden=0')->select();
        $this->assign("ticketType_array",$ticketType_array);
        
        $this->assign('title','添加导航');
        $this->assign("navcid",$cid);
        $this->display();
   	}
   	public function type_add_post(){
   		if (IS_POST) {
            $data=I("post.");
       		$storeArray  =   $this->storeArray;
       		$data['shore_id']=$storeArray['id'];
            if($data['label']==null){
                $this->ajax_r(0,"请输入导航名称",array('url' => U('Shop/index')));
            }
            if(empty($data['icon'])){
                $data['icon']=$data['UpFilePathInfo'];
            }
            if ($this->nav_model->create($data)) {
                print_r($this->nav_model->create($data));
                $result=$this->nav_model->add();
                print_r($this->nav_model->getLastSql());
                if ($result!==false) {
                    $parentid = $_POST['parentid']==0?"0":$_POST['parentid'];
                    if(empty($parentid)){
                        $data['path']="0-$result";
                    }else{
                        $parent=$this->nav_model->where("id=$parentid")->find();
                        $data['path']=$parent[path]."-$result";
                    }
                    $data['id']=$result;
                    $this->nav_model->save($data);
                    $this->ajax_r(1,"添加成功",array('url' => U('Shop/type')));
                  
                } else {
                    $this->ajax_r(0,"添加失败");
                }
            } else {
                $this->ajax_r(0,"添加失败");
            }
        }
   	}
   	public function type_edit(){
   		$storeArray  =   $this->storeArray;
       	$shore_id=$storeArray['id'];
        $id=intval(I("get.id"));
        $result = $this->nav_model->where("shore_id=".$shore_id." and id!=$id")->order(array("listorder" => "ASC"))->select();
         import("Think.Tree");
        $tree = new \Tree();
        $tree->icon = array('&nbsp;│ ', '&nbsp;├─ ', '&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
        $parentid= I("get.parentid");
        foreach ($result as $r) {
            $r['str_manage'] = '<a href="' . U("Menu/add", array("parentid" => $r['id'], "menuid" => I("get.menuid"))) . '">添加子菜单</a> | <a href="' . U("Menu/edit", array("id" => $r['id'], "menuid" => I("get.menuid"))) . '">修改</a> | <a class="js-ajax-delete" href="' . U("Menu/delete", array("id" => $r['id'], "menuid" => I("get.menuid"))) . '">删除</a> ';
            $r['status'] = $r['status'] ? "显示" : "隐藏";
            $r['selected'] = $r['id']==$parentid?"selected":"";
            $array[] = $r;
        }
        
        $tree->init($array);
        $str = "<tr>
                <td><input name='listorders[\$id]' type='text' size='3' value='\$listorder' class='input'></td>
                <td>\$id</td>
                <td >\$spacer\$label</td>
                <td>\$status</td>
                <td>\$str_manage</td>
            </tr>";
        $str="<option value='\$id' \$selected>\$spacer\$label</option>";
        $nav_trees = $tree->get_tree(0, $str);
        $this->assign("nav_trees", $nav_trees);
        
        $nav=$this->nav_model->where("id=$id")->find();
        $this->assign($nav);
       	$this->assign('title','编辑导航');
        $this->assign("navcid",$cid);
        $this->display();
   	}
   	
   	public function type_edit_post(){
   		if (IS_POST) {
            $parentid=empty($_POST['parentid'])?"0":$_POST['parentid'];
            if(empty($parentid)){
                $_POST['path']="0-".$_POST['id'];
            }else{
                $parent=$this->nav_model->where("id=$parentid")->find();
                    
                $_POST['path']=$parent['path']."-".$_POST['id'];
            }
            
            $data=I("post.");
            if($data['label']==null){
                $this->ajax_r(0,"请输入导航名称");
            }
            if ($this->nav_model->create($data)) {
                if ($this->nav_model->save() !== false) {
                    $this->ajax_r(1,"保存成功",array('url' => U('Shop/type')));
                } else {
                    $this->ajax_r(0,"保存失败");
                }
            } else {
                $this->ajax_r(0,"保存失败");
            }
        } 
   	}
   	public function type_del(){
   		$id = intval(I("get.id"));;
        $count = $this->nav_model->where(array("parentid" => $id))->count();
        if ($count > 0) {
            $this->error("该菜单下还有子菜单，无法删除！");
        }
        if ($this->nav_model->delete($id)!==false) {
            $this->success("删除菜单成功！");
        } else {
            $this->error("删除失败！");
        }
   	}
   	
   	function shop_type_set(){
   		$data=I('post.');
        $data['store_type_id']=implode(',',$data['store_type_id']);

   		$shop=M('shop');
   		$adids=explode(',',$data['adids']);
   		$shop_type=$data['store_type_id'];
   		if($shop_type!='-1'&&$shop_type!='0'){
   			foreach($adids as $key=>$value){
	   			if($value){
	   				$map['id']=$value;
	   				$map['store_type_id']=$shop_type;
	   				$shop->save($map);
	   			}
	   		}
            $this->ajax_r(1,"更新成功");
   		}else{
            $this->ajax_r(0,"没有选择分类!!");
   		}
   	}

    function transport(){
    	$model_transport	= M('transport');
    	$transport_extend =M('transport_extend');
    	$storeArray  =   $this->storeArray;
       	$shore_id=$storeArray['id'];
		$count = $model_transport->where(array('store_id'=>$shore_id))->count();
		$this->assign('count',$count);
        $Page       = new \Think\Page($count,4);// 实例化分页类 传入总记录数
        $show       = $Page->show1();// 分页显示输出
       
		$list = $model_transport->where(array('store_id'=>$shore_id))->limit($Page->firstRow.','.$Page->listRows)->select();
		
		if (!empty($list) && is_array($list)){
			
			foreach ($list as $key=>$v) {
				$extend = $transport_extend->where('transport_id='.$v['id'])->select();
				$list[$key]['extend']= $extend ;
	        }
		}
		$this->assign('list',$list);
		$this->assign('page',$show);
		$this->display();
    }
    function transportadd(){
    	$area=getAreaList();
    	$this->assign('area',$area);
    	$this->display();
    }
    
    function transportedit(){
    	$area=getAreaList();
    	$id=I('get.id');
    	$transport =M('transport');
    	$transport_info=$transport->find($id);
    	$this->assign('transport_info',$transport_info);
    	
    	$transport_extend =M('transport_extend');
    	$extend = $transport_extend->where('transport_id='.$id)->select();
    	
    	$this->assign('extend',$extend);
    	$this->assign('area',$area);
    	$this->display();
    }
    
    function transportdel(){
    	$id=I('get.id');
    	$transport =M('transport');
    	$transport->delete($id);
    	$transport_extend =M('transport_extend');
    	$transport_extend->where('transport_id='.$id)->delete();
    	$this->redirect('Shop/transport');
    }
    
    function transportsave(){
    	if($_POST){
    		$transport =M('transport');
    		$transport_extend =M('transport_extend');
    		$storeArray  =   $this->storeArray;
       		$shore_id=$storeArray['id'];
       		
       		$data=I('post.');
       		
			$trans_info = array();
			$trans_info['title'] 		= $data['title'];	
			$trans_info['send_tpl_id']  = 1;
			$trans_info['store_id'] 	= $shore_id;
			$trans_info['update_time'] 	= time();
			
			if (is_numeric($data['transport_id'])){
				//编辑时，删除所有附加表信息
				$trans_info['id'] = $data['transport_id'];
				$transport_id = $data['transport_id'];
				$transport->save($trans_info);
				$transport_extend->where('transport_id='.$transport_id)->delete();
				$trans=$data['transport_id'];
			}else{
				//新增
				$trans=$transport->add($trans_info);
			}
			//保存默认运费
			if (is_array($data['default']['kd'])){
				$a = $data['default']['kd'];
				$trans_list[0]['area_id'] = '';
				$trans_list[0]['area_name'] = '全国';
				$trans_list[0]['snum'] = $a['start'];
				$trans_list[0]['sprice'] = $a['postage'];
				$trans_list[0]['xnum'] = $a['plus'];
				$trans_list[0]['xprice'] = $a['postageplus'];
				$trans_list[0]['is_default'] = 1;
				$trans_list[0]['transport_id'] = $trans;
				$trans_list[0]['transport_title'] = $data['title'];
				$trans_list[0]['top_area_id'] = '';
				
			}
			
			//保存自定义地区的运费设置
			$areas = $data['areas']['kd'];
			$special = $data['special']['kd'];
			if (is_array($areas) && is_array($special)){
				//$key需要加1，因为快递默认运费占了第一个下标
				foreach ($special as $key=>$value) {
				    if (empty($areas[$key])) continue;
					$areas[$key] = explode('|||',$areas[$key]);
					$trans_list[$key+1]['area_id'] = ','.$areas[$key][0].',';
					$trans_list[$key+1]['area_name'] = $areas[$key][1];
					$trans_list[$key+1]['snum'] = $value['start'];
					$trans_list[$key+1]['sprice'] = $value['postage'];
					$trans_list[$key+1]['xnum'] = $value['plus'];
					$trans_list[$key+1]['xprice'] = $value['postageplus'];
					$trans_list[$key+1]['is_default'] = 2;
					$trans_list[$key+1]['transport_id'] = $trans;
					$trans_list[$key+1]['transport_title'] = $data['title'];
					//计算省份ID
					$province = array();
					$tmp = explode(',',$areas[$key][0]);
					if (!empty($tmp) && is_array($tmp)){
						$city = getCity_array();
						foreach ($tmp as $t) {
							$pid = $city[$t];
							if (!in_array($pid,$province) && !empty($pid))$province[] = $pid;
						}
					}
					if (count($province)>0){
						$trans_list[$key+1]['top_area_id'] = ','.implode(',',$province).',';
					}else{
						$trans_list[$key+1]['top_area_id'] = '';
					}
					$i++;
					
				}
			}
			
			foreach($trans_list as $key=>$v){
				$transport_extend->add($v);
			}
			$this->redirect('Shop/transport');

		}
    }
    
    function evaluate(){
    	$where='';
    	if($_GET['startDate']&&$_GET['endDate']){
    		$startDate=strtotime($_GET['startDate']);
  			$endDate=strtotime($_GET['endDate']);
    		$where.=" and yt_order_goods_evaluate.addtime>=".$startDate." and yt_order_goods_evaluate.addtime<=".$endDate;
    	}
    	if($_GET['startDate']&&$_GET['endDate']==null){
    		$startDate=strtotime($_GET['startDate']);
    		$where.=" and yt_order_goods_evaluate.addtime>=".$startDate;
    	}
    	if($_GET['startDate']==null&&$_GET['endDate']){
    		$endDate=strtotime($_GET['endDate']);
    		$where.=" and yt_order_goods_evaluate.addtime<=".$endDate;
    	}
    	
    	if($_GET['explain_type']){
    		if($_GET['explain_type']==1){
    			$where.=" and yt_order_goods_evaluate.scores<=5 and yt_order_goods_evaluate.scores>=4";
    		}
    		if($_GET['explain_type']==2){
    			$where.=" and yt_order_goods_evaluate.scores=3 ";
    		}
    		if($_GET['explain_type']==3){
    			$where.=" and yt_order_goods_evaluate.scores<=2 and yt_order_goods_evaluate.scores>=1";
    		}
    	}
    	
    	$order_goods_evaluate=M('order_goods_evaluate');
    	$storeArray  =   $this->storeArray;
       	$shore_id=$storeArray['id'];
   		$evaluate_count=$order_goods_evaluate
   						->join("yt_shop on yt_shop.id = yt_order_goods_evaluate.goods_id ",'left')
    					->where("yt_order_goods_evaluate.is_show=1 and yt_shop.store_id=$shore_id".$where)
    					->count();
    
    	$this->assign('evaluate_count',$evaluate_count);
	    $Page       = new \Think\Page($evaluate_count,6);// 实例化分页类 传入总记录数
		$Page->setConfig('header','条记录');
	    $Page->setConfig('prev','上一页');
	    $Page->setConfig('next','下一页');
	    $show = $Page->show();// 分页显示输出
	  	$evaluate_list=$order_goods_evaluate
	  					->field("yt_order_goods_evaluate.*,yt_shop.title,yt_shop.image as shop_image")
	  					->join("yt_shop on yt_shop.id = yt_order_goods_evaluate.goods_id ",'left')
    					->where("yt_order_goods_evaluate.is_show=1 and yt_shop.store_id=$shore_id".$where)
	  					->limit($Page->firstRow.','.$Page->listRows)
	  					->order('yt_order_goods_evaluate.id desc')
	  					->select();
	  
    	$this->assign('evaluate_list',$evaluate_list);
    	$this->assign('evaluate_page',$show);
    	$this->display();
    }
   
	function replyevaluateajax(){
		$order_goods_evaluate=M('order_goods_evaluate');
		if($_POST){
			$data=I('post.');
			if($data['replyType']==1){
				$info['id']=$data['evaluate_id'];
				$info['explain_first']=$data['evaluate_reply'];
				$rs=$order_goods_evaluate->save($info);
				
			}
			if($data['replyType']==2){
				$info['id']=$data['evaluate_id'];
				$info['again_explain']=$data['evaluate_reply'];
				$rs=$order_goods_evaluate->save($info);
			}
		}
		if($rs){
            $this->ajax_r(1,"回复成功");
		}else{
            $this->ajax_r(0,"回复失败");
		}
		
	}
	
	
	function angel_list(){
        $storeArray  =   $this->storeArray;
        $shore_id=$storeArray['id'];
        $angel=M('angel');
        $rs=$angel
            ->field('yt_users.phone,yt_angel.*')
            ->join('yt_users on yt_users.id=yt_angel.uid')
            ->where('yt_angel.type=2 and yt_angel.type_id='.$shore_id)->select();
        $this->assign('list',$rs);
        $this->display();
    }

    function add_angel(){
        $storeArray  =   $this->storeArray;

        if($_POST){
            $data['type_id']=$storeArray['id'];
            $data['uid']=I('post.uid');
            $data['add_type']=1;
            $data['type']=2;
            $rs= M('angel')->add($data);
            if($rs){
                $this->ajax_r(1,"添加代言成功",array('url' => U('Shop/angel_list')));
            }else{
                $this->ajax_r(0,"添加代言失败");
            }
        }ELSE{
            $this->assign('storeArray',$storeArray);
            $this->display();
        }
    }

    public function search_phone2(){
        $phone=I('get.phone');
        $users=M('users');
        $storeArray  =   $this->storeArray;
        $shore_id=$storeArray['id'];
        $rs=$users->where('phone='.$phone)->find();
        if($rs){
            $angel=M('angel');
            $c_rs=$angel->where('type=2 and type_id='.$shore_id.' and uid='.$rs['id'])->select();
            if($c_rs){
                $this->ajaxReturn(1);
            }else{
                $this->ajaxReturn($rs);
            }
        }else{
            $this->ajaxReturn(0);
        }

    }

    public function  del_angel(){
        $angel=M('angel');
        $id=I('get.id');
        $rs=$angel->delete($id);
        $this->redirect("Shop/angel_list");
    }
}